import { createRouter, createWebHashHistory } from 'vue-router'
import { storeToRefs } from 'pinia'
import { userStore } from '@/stores/mqttStore'

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/main',
      name: 'main',
      component: () => import('@/view/MainView.vue'),
      children:[
        {
          path: '/',
          name: 'home',
          component: () => import('@/view/HomeView.vue')
        },
        {
          path: '/user',
          name: 'user',
          component: () => import('@/view/UserView.vue')
        },
        {
          path: '/setting',
          name: 'setting',
          component: () => import('@/view/SettingView.vue')
        },
        {
          path: '/setting',
          name: 'setting',
          component: () => import('@/view/SettingView.vue')
        }
      ]
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/view/LoginView.vue')
    },
    {
      path: '/invite',
      name: 'invite',
      component: () => import('@/view/InviteView.vue')
    },
    {
      path: '/chat',
      name: 'chat',
      component: () => import('@/view/ChatView.vue')
    }
  ]
})

router.beforeEach((to, from, next) => {
  /* 路由发生变化修改页面title */
  if (to.meta.title) {
    document.title = to.meta.title
  }

  if(checkLogin() || to.path == '/login'){
    next()
  }else{
    next('/login')
  }
})

const checkLogin = () => {
  const { uid } = storeToRefs(userStore())
  return uid.value ? true : false
}

export default router